package com.nn.service.impl;

import com.nn.R;
import com.nn.constents.SystemConstants;
import com.nn.entity.LoginUser;
import com.nn.entity.SysUser;
import com.nn.service.BlogLoginService;
import com.nn.utils.BeanCopyUtils;
import com.nn.utils.JwtUtil;
import com.nn.utils.RedisCache;
import com.nn.vo.BlogUserLoginVO;
import com.nn.vo.UserInfoVO;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;


@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public R login(SysUser user) {
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (Objects.isNull(authenticate))
            throw new RuntimeException("用户名或密码错误！");
        //获取userid生成token
        LoginUser loginUser= (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(id.toString());

        //将token存入redis
        redisCache.setCacheObject(SystemConstants.REDIS_KEY +id,loginUser);
        //封装响应对象
        UserInfoVO userInfoVO = BeanCopyUtils.copyBean(loginUser, UserInfoVO.class);
        BlogUserLoginVO vo = new BlogUserLoginVO(jwt,userInfoVO);
        return R.okResult(vo);
    }


    /**
     * 退出登录
     * @return
     */
    @Override
    public R logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        Long id = user.getUser().getId();
        redisCache.deleteObject(SystemConstants.REDIS_KEY+id);
        return R.okResult();
    }
}
